const express = require('express');
const cors = require('cors');
const sequelize = require('./config/database');
const fs = require('fs').promises;
const path = require('path');
const models = require('./models');
const authRoutes = require('./routes/authRoutes');
const merchantAuthRoutes = require('./routes/merchantAuthRoutes');

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/merchant', merchantAuthRoutes);

// 导入SQL文件函数
async function importSQL() {
  try {
    const sqlPath = path.join(__dirname, '../../database.sql');
    const sql = await fs.readFile(sqlPath, 'utf8');
    const statements = sql.split(';').filter(statement => statement.trim());
    
    for (const statement of statements) {
      if (statement.trim()) {
        await sequelize.query(statement + ';');
      }
    }
    console.log('SQL文件导入成功');
  } catch (error) {
    console.error('SQL文件导入失败:', error);
  }
}

// 数据库连接和初始化
async function initializeDatabase() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 同步所有模型
    await sequelize.sync();
    console.log('数据库模型同步成功');
    
    // 导入SQL文件
    await importSQL();
    
    console.log('数据库初始化完成');
  } catch (error) {
    console.error('数据库初始化失败:', error);
  }
}

// 基础路由
app.get('/', (req, res) => {
  res.send('服务器运行正常');
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, async () => {
  console.log(`服务器运行在端口 ${PORT}`);
  await initializeDatabase();
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('服务器内部错误');
}); 